<template>
  <view class="product-detail">
    <!-- 轮播图 -->
    <view class="swiper-container">
      <swiper 
        circular 
        indicator-dots 
        autoplay 
        interval="3000" 
        duration="500" 
        indicator-active-color="#e5394d"
      >
        <swiper-item v-for="(item, index) in product.images" :key="index">
          <image class="slide-image" :src="item" mode="aspectFill" @click="previewImage(index)"></image>
        </swiper-item>
      </swiper>
      <view class="indicator">{{ currentSwiper + 1 }}/{{ product.images.length }}</view>
    </view>
    
    <!-- 商品基本信息 -->
    <view class="basic-info">
      <view class="price-row">
        <view class="price">{{ product.price.toFixed(2) }}</view>
        <view class="original-price" v-if="product.originalPrice">{{ product.originalPrice.toFixed(2) }}</view>
        <view class="discount-tag" v-if="product.discount">{{ product.discount }}折</view>
        <view class="sold-count">已售{{ product.sales }}件</view>
      </view>
      <view class="product-name">{{ product.name }}</view>
      <view class="product-desc">{{ product.subtitle }}</view>
    </view>
    
    <!-- 规格选择 -->
    <view class="specs-block">
      <view class="spec-item" @click="openSpecSelector">
        <view class="spec-name">规格</view>
        <view class="spec-value">{{ selectedSpec || '请选择规格' }}</view>
        <text class="arrow">></text>
      </view>
      <view class="spec-item">
        <view class="spec-name">配送</view>
        <view class="spec-value">全国包邮</view>
      </view>
    </view>
    
    <!-- 商品评价预览 -->
    <view class="section-block reviews-block">
      <view class="section-header">
        <view class="title">商品评价 ({{ product.reviewCount || 0 }})</view>
        <view class="more" @click="viewAllReviews">查看全部 ></view>
      </view>
      
      <view class="review-list" v-if="product.reviews && product.reviews.length > 0">
        <view class="review-item" v-for="(review, index) in product.reviews" :key="index">
          <view class="user-info">
            <image class="avatar" :src="review.avatar || '/static/images/avatar-default.png'"></image>
            <view class="nickname">{{ review.nickname }}</view>
            <view class="date">{{ review.date }}</view>
          </view>
          <view class="review-content">{{ review.content }}</view>
          <view class="review-images" v-if="review.images && review.images.length > 0">
            <image 
              class="image" 
              v-for="(img, imgIndex) in review.images" 
              :key="imgIndex" 
              :src="img" 
              mode="aspectFill"
              @click="previewReviewImage(review.images, imgIndex)"
            ></image>
          </view>
          <view class="spec-info">{{ review.specificationName }}</view>
        </view>
      </view>
      
      <view class="empty-review" v-else>
        暂无评价
      </view>
    </view>
    
    <!-- 商品详情 -->
    <view class="section-block detail-content">
      <view class="section-header">
        <view class="title">商品详情</view>
      </view>
      <view class="html-content">
        <rich-text :nodes="product.detail"></rich-text>
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="action-icons">
        <view class="action-item" @click="navToHome">
          <text class="icon">🏠</text>
          <text class="text">首页</text>
        </view>
        <view class="action-item" @click="toggleFavorite">
          <text class="icon" :class="{ active: isFavorite }">{{ isFavorite ? '❤️' : '♡' }}</text>
          <text class="text">收藏</text>
        </view>
        <view class="action-item" @click="navToCart">
          <text class="icon">🛒</text>
          <text class="text">购物车</text>
          <view class="badge" v-if="cartCount > 0">{{ cartCount }}</view>
        </view>
      </view>
      
      <view class="button-group">
        <view class="btn add-cart-btn" @click="handleAddToCart">加入购物车</view>
        <view class="btn buy-now-btn" @click="handleBuyNow">立即购买</view>
      </view>
    </view>
    
    <!-- 规格选择弹窗 -->
    <uni-popup ref="specPopup" type="bottom">
      <view class="popup-specs">
        <view class="popup-content">
          <view class="product-info">
            <image class="product-image" :src="product.images[0]" mode="aspectFill"></image>
            <view class="info">
              <view class="price">{{ product.price.toFixed(2) }}</view>
              <view class="selected-spec">已选：{{ selectedSpec || '请选择规格' }}</view>
              <view class="stock">库存：{{ product.stock || 999 }}件</view>
            </view>
          </view>
          
          <view class="specs-list">
            <view class="spec-group">
              <view class="group-title">规格</view>
              <view class="specs">
                <view 
                  v-for="(spec, index) in product.specs" 
                  :key="index"
                  :class="['spec', selectedSpecIndex === index ? 'active' : '']"
                  @click="selectSpec(index)"
                >{{ spec }}</view>
              </view>
            </view>
          </view>
          
          <view class="quantity-wrapper">
            <view class="label">购买数量</view>
            <uni-number-box 
              :min="1" 
              :max="99" 
              v-model="quantity"
            ></uni-number-box>
          </view>
          
          <view class="popup-btns">
            <view class="popup-btn add-cart" @click="addToCart">加入购物车</view>
            <view class="popup-btn buy-now" @click="buyNow">立即购买</view>
          </view>
        </view>
        
        <text class="close-btn" @click="closeSpecSelector">×</text>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import productApi from '@/api/product.js';
import userApi from '@/api/user.js';
import '@/styles/pages/product/detail.scss';

export default {
  data() {
    return {
      id: null,
      product: {
        id: 0,
        name: '',
        subtitle: '',
        price: 0,
        originalPrice: 0,
        discount: 0,
        sales: 0,
        goodRate: 0,
        stock: 999,
        reviewCount: 0,
        images: [],
        specs: [],
        detail: '',
        reviews: []
      },
      selectedSpec: '',
      selectedSpecIndex: -1,
      quantity: 1,
      actionType: 'add', // 'add' 或 'buy'
      isFavorite: false,
      currentSwiper: 0
    };
  },
  computed: {
    ...mapGetters({
      cartCount: 'cart/totalCount',
      isLoggedIn: 'user/isLoggedIn'
    })
  },
  onLoad(options) {
    if (options.id) {
      this.id = options.id;
      this.getProductDetail();
      this.checkFavorite();
    }
  },
  methods: {
    ...mapActions({
      addToCartAction: 'cart/addToCart'
    }),
    
    // 获取商品详情
    async getProductDetail() {
      uni.showLoading({ title: '加载中...' });
      
      try {
        const res = await productApi.getProductDetail(this.id);
        this.product = res;
        
        // 获取商品评价
        this.getProductReviews();
        
        uni.hideLoading();
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '加载商品失败',
          icon: 'none'
        });
      }
    },
    
    // 获取商品评价
    async getProductReviews() {
      try {
        const res = await productApi.getProductReviews(this.id, {
          page: 1,
          limit: 2
        });
        
        this.product.reviews = res.data;
        this.product.reviewCount = res.total;
      } catch (error) {
        console.error('获取评价失败', error);
      }
    },
    
    // 检查是否已收藏
    async checkFavorite() {
      if (!this.isLoggedIn) return;
      
      try {
        const res = await userApi.checkFavorite(this.id);
        this.isFavorite = res;
      } catch (error) {
        console.error('检查收藏状态失败', error);
      }
    },
    
    // 切换收藏状态
    async toggleFavorite() {
      if (!this.isLoggedIn) {
        uni.navigateTo({ url: '/pages/login/index' });
        return;
      }
      
      try {
        if (this.isFavorite) {
          await userApi.removeFavorite(this.id);
          this.isFavorite = false;
          uni.showToast({
            title: '已取消收藏',
            icon: 'success'
          });
        } else {
          await userApi.addFavorite(this.id);
          this.isFavorite = true;
          uni.showToast({
            title: '收藏成功',
            icon: 'success'
          });
        }
      } catch (error) {
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        });
      }
    },
    
    // 预览图片
    previewImage(index) {
      uni.previewImage({
        current: index,
        urls: this.product.images
      });
    },
    
    // 预览评价图片
    previewReviewImage(images, index) {
      uni.previewImage({
        current: index,
        urls: images
      });
    },
    
    // 打开规格选择
    openSpecSelector() {
      this.actionType = 'add';
      this.$refs.specPopup.open();
    },
    
    // 关闭规格选择
    closeSpecSelector() {
      this.$refs.specPopup.close();
    },
    
    // 选择规格
    selectSpec(index) {
      this.selectedSpecIndex = index;
      this.selectedSpec = this.product.specs[index];
    },
    
    // 加入购物车按钮点击
    handleAddToCart() {
      this.actionType = 'add';
      if (!this.selectedSpec) {
        this.openSpecSelector();
      } else {
        this.addToCart();
      }
    },
    
    // 立即购买按钮点击
    handleBuyNow() {
      this.actionType = 'buy';
      if (!this.selectedSpec) {
        this.openSpecSelector();
      } else {
        this.buyNow();
      }
    },
    
    // 加入购物车
    addToCart() {
      if (!this.selectedSpec) {
        uni.showToast({
          title: '请选择规格',
          icon: 'none'
        });
        return;
      }
      
      const cartItem = {
        id: this.product.id,
        name: this.product.name,
        image: this.product.images[0],
        price: this.product.price,
        spec: this.selectedSpec,
        quantity: this.quantity,
        selected: true
      };
      
      this.addToCartAction(cartItem);
      
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      });
      
      this.closeSpecSelector();
    },
    
    // 立即购买
    buyNow() {
      if (!this.selectedSpec) {
        uni.showToast({
          title: '请选择规格',
          icon: 'none'
        });
        return;
      }
      
      const orderItems = [{
        id: this.product.id,
        name: this.product.name,
        image: this.product.images[0],
        price: this.product.price,
        spec: this.selectedSpec,
        quantity: this.quantity
      }];
      
      // 跳转到结算页
      uni.navigateTo({
        url: `/pages/order/checkout?items=${encodeURIComponent(JSON.stringify(orderItems))}`
      });
      
      this.closeSpecSelector();
    },
    
    // 查看所有评价
    viewAllReviews() {
      uni.navigateTo({
        url: `/pages/product/review?id=${this.id}`
      });
    },
    
    // 跳转到首页
    navToHome() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    },
    
    // 跳转到购物车
    navToCart() {
      uni.switchTab({
        url: '/pages/cart/cart'
      });
    }
  }
};
</script> 